package com.syncomponents.util;

import com.sunkey.log.util.JsonUtil;
import com.syncomponents.core.EnumAck;
import com.syncomponents.core.MessageConstant;
import com.syncomponents.message.BaseMessage;
import com.syncomponents.message.ResponseMessage;
import commonj.sdo.DataObject;
import commonj.sdo.helper.DataFactory;
import commonj.sdo.helper.XMLDocument;
import commonj.sdo.helper.XMLHelper;

/**
 * 消息工具类
 * 
 * @author sunkey
 * @date Jan 29, 2015
 */
public abstract class MessageUtil {

    public static String getErrorResponseMessage(String orignMsg, String errorMessage) {
        if (orignMsg.startsWith("{")) {
            return getJSON(orignMsg, errorMessage);
        } else {
            return getXML(orignMsg, errorMessage);
        }

    }

    @SuppressWarnings("rawtypes")
    private static String getJSON(String orignMsg, String errorMessage){
        ResponseMessage message = new ResponseMessage();
        BaseMessage orignMessage = JsonUtil.fromJson(orignMsg, BaseMessage.class);
        message.setAck(EnumAck.Failure.toString());
        message.setMessage(errorMessage);
        message.setAction(orignMessage.getAction());
        message.setMsgType(orignMessage.getMsgType());
        
        return JsonUtil.toJson(message);
    }

    private static String getXML(String orignMsg, String errorMessage) {
        XMLDocument xmlDoc = XMLHelper.INSTANCE.load(orignMsg);
        final DataObject dobj = xmlDoc.getRootObject();
        String msgType = dobj.getString(MessageConstant.MESSAGE_TYPE);
        String action = dobj.getString(MessageConstant.MESSAGE_ACTION);

        DataObject responseDO = DataFactory.INSTANCE.create(MessageConstant.RESPONSE_NAMESPACE,
                MessageConstant.ELEMENT_RESPONSE);
        if (msgType != null) {
            responseDO.setString(MessageConstant.MESSAGE_TYPE, msgType);
        }
        if (action != null) {
            responseDO.setString(MessageConstant.MESSAGE_ACTION, action);
        }
        responseDO.setString(MessageConstant.MESSAGE_ACK, EnumAck.Failure.toString());
        responseDO.setString(MessageConstant.MESSAGE_MESSAGE, errorMessage);

        return XMLHelper.INSTANCE
                .save(responseDO, MessageConstant.RESPONSE_NAMESPACE, MessageConstant.ELEMENT_RESPONSE);
    }

}
